from django_redis import get_redis_connection
from rest_framework import serializers

from .models import OAuthQQUser
from users.models import User
from .utils import decode_sign_openid


class OAuthQQUserSerializer(serializers.Serializer):
    access_token = serializers.CharField(label='加密的openid')
    mobile = serializers.RegexField(label="手机号", regex=r'^1[3-9]\d{9}$')

    sms_code = serializers.CharField(label='短信', min_length=6,max_length=6)

    password = serializers.CharField(min_length=8,max_length=20,label='密码')

    def validate(self, attrs):
        openid = decode_sign_openid(attrs["access_token"])
        if not openid:
            raise serializers.ValidationError('openid错误')

        mobile = attrs['mobile']
        sms_code=attrs['sms_code']

        redis_conn = get_redis_connection('code')
        redis_sms_code = redis_conn.get('sms_code_%s' % mobile)

        if not redis_sms_code:
            raise serializers.ValidationError("短信验证码过期")

        if sms_code != redis_sms_code.decode():
            raise serializers.ValidationError("短信验证码错误")

        user= None
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass

        else:
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError('密码错误')

        attrs['openid'] = openid
        attrs['user'] = user

        return attrs

    def create(self, validated_data):
        openid = validated_data['openid']
        user = validated_data['user']

        if not user:
            user = User.objects.create_user(
                username=validated_data['mobile'],
                password=validated_data['password'],
                mobile=validated_data['mobile'],
            )

        OAuthQQUser.objects.create(openid=openid,user=user)

        return user